/** KA 公用类 v1.0.0 **/
if (!String.prototype.replaceAll) {
    String.prototype.replaceAll = function (str1, str2) {
        return this.replace(new RegExp(str1, "gm"), str2);
    }
}
$.getUrlParam = function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}
//ka统一工具类
var ka = {
    uuidStr: function () {//获取UUID
        var s = [];
        var hexDigits = "0123456789abcdef";
        for (var i = 0; i < 36; i++) {
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
        s[8] = s[13] = s[18] = s[23] = "-";
        var uuid = s.join("").replaceAll("-", "").replace(/\s+/g, '');;
        return uuid;
    },
    dateFormat: function (fmt, date) { // 格式化时间 YYYY MM-DD HH:mm:ss
        let ret;
        const opt = {
            "Y+": date.getFullYear().toString(),        // 年
            "m+": (date.getMonth() + 1).toString(),     // 月
            "d+": date.getDate().toString(),            // 日
            "H+": date.getHours().toString(),           // 时
            "M+": date.getMinutes().toString(),         // 分
            "S+": date.getSeconds().toString()          // 秒
            // 有其他格式化字符需求可以继续添加，必须转化成字符串
        };
        for (let k in opt) {
            ret = new RegExp("(" + k + ")").exec(fmt);
            if (ret) {
                fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
            };
        };
        return fmt;
    },
    watermark: function (id) { //页面添加水印
        $(id).watermark({
            texts: ["Stanley", "知行合一"], //水印文字
            textColor: "#eee", //文字颜色
            textFont: '13px 微软雅黑', //字体
            width: 100, //水印文字的水平间距
            height: 100,  //水印文字的高度间距（低于文字高度会被替代）
            textRotate: -30 //-90到0， 负数值，不包含-90
        })
    },
    ajax: function (myOption) {//统一的AJAX请求
        //loading 加载层ID
        var uuidStrIds = ka.uuidStr();
        //设置参数
        var option = {
            url: myOption.url,
            contentType: "application/json;charset=utf-8",
            type: myOption.type == undefined ? 'POST' : myOption.type,
            async: myOption.async == undefined ? false : myOption.async,
        }

        kalog.outLogs(["请求方式(url):", myOption.url]);
        kalog.outLogs(["请求方式(type):", myOption.type]);
        kalog.outLogs(["是否异步(async):", myOption.async]);
        //参数
        if (!(myOption["data"] == undefined)) {
            myOption.data["frontEndUrl"] = kaValue.ctx();
            option.data = JSON.stringify(myOption.data);
            kalog.outLogs(["参数(Data):", myOption.data]);
        } else {
            if (option.type == "GET") {
                option.data = { "frontEndUrl": kaValue.ctx() };
            } else {
                option.data = JSON.stringify({ "frontEndUrl": kaValue.ctx() });
            }
        }
        if (!kaValue.isBackend) { // 判断是否后端
            var cleanedUrl = ka.removeAddressPortAndQuery(option.url);
            cleanedUrl = encodeURIComponent(Base64.encode(cleanedUrl));
            cleanedUrl = cleanedUrl.replaceAll(/\//g, ".");
            cleanedUrl = cleanedUrl.replaceAll("%", ".");
            cleanedUrl = "ka." + cleanedUrl;
            option.url = kaValue.qdCtx() + "/json/" + cleanedUrl + ".json";
            option.type = "GET";
        }
        //开始
        option.beforeSend = function (xhr) {
            if (myOption.noloading == undefined) {
                myOption.noloading = true;
            }
            if (myOption.token == undefined || myOption.token == null || myOption.token == "") {
                xhr.setRequestHeader("Authorization", 'Bearer ' + kaToken.get());
                kalog.outLogs(["Token(Token):", kaToken.get()]);
            }
            if (myOption.noloading) {
                var sertlayui = top.layui.layer.msg('数据加载中', {
                    icon: 16,
                    time: 0,
                    shade: [0.6, '#FFF'], // 遮罩透明度
                    shadeClose: false, // 点击遮罩区域，关闭弹层
                });
                this.kaUuidStrIds = uuidStrIds;
                top.ka_top_loadIndexMap.set(uuidStrIds, sertlayui);
            }
            if (typeof myOption.beforeSend !== 'undefined') {
                myOption.beforeSend();
            }
            top.ka_top_ajaOptionIndexMap.set(uuidStrIds, myOption);
        };
        //成功
        option.success = function (re) {
            var kaUuidStrIds = this.kaUuidStrIds;
            top.layer.close(top.ka_top_loadIndexMap.get(uuidStrIds));
            var ajaOptionMap = top.ka_top_ajaOptionIndexMap.get(uuidStrIds)
            if (kaValue.isBackend && kaValue.isGeneratedFile) {
                var cleanedUrl = ka.removeAddressPortAndQuery(ajaOptionMap.url);
                cleanedUrl = encodeURIComponent(Base64.encode(cleanedUrl))
                cleanedUrl = cleanedUrl.replaceAll(/\//g, ".");
                cleanedUrl = cleanedUrl.replaceAll("%", ".");
                cleanedUrl = "ka." + cleanedUrl;
                $.ajax({
                    url: kaValue.qdCtx() + "/json/" + cleanedUrl + ".json",
                    dataType: 'json',
                    async: false,
                    success: function (data) {
                        console.log('文件存在，数据加载成功:', data);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        ka.downloadJsonFile(re, cleanedUrl + '.json');
                    }
                });
            }
            kalog.outLogs(["返回结果(success):", re]);
            if (kaValue.isGeneratedFile) {
                //验证码
                if (ajaOptionMap != undefined) {

                } else {
                }
            }
            if (typeof myOption.success !== 'undefined') {
                if (re.code == "401" && re.msg.indexOf("认证失败，无法访问系统资源") > -1) {
                    var url = top.window.location.href;
                    if (url.indexOf("home.html") == -1 && url.indexOf("login.html") == -1) {
                        sessionStorage.setItem("indexpage", url);
                    }
                    var kaindexpagestr = sessionStorage.getItem("indexpage");
                    if (kaindexpagestr != undefined && kaindexpagestr != null && kaindexpagestr != "") {
                        kaindexpagestr = "?indexpage=" + encodeURIComponent(encodeURI(kaindexpagestr));;
                    } else {
                        kaindexpagestr = "";
                    }
                    if (window.location.href.indexOf("login.html") == -1) {
                        kaCookie.clear("Admin-Token");
                        kaCookie.clear("Authorization");
                        kaCookie.clear("JSESSIONID");
                        kaCookie.clear("password");
                        kaCookie.clear("password");
                        kaToken.clear();
                        window.location.href = "login.html" + kaindexpagestr
                    }
                } else {
                    myOption.success(re);
                }
            }
        }
        //错误
        option.error = function (e) {
            top.layer.close(top.ka_top_loadIndexMap.get(uuidStrIds))
            kalog.outLogs(["返回结果(error):", e]);
            if (typeof myOption.error !== 'undefined') {
                myOption.error(e);
            } else {
                var opt = {};
                opt.msg = "请求数据失败！" + JSON.stringify(e);
                opt.code = "500";
                kaMsg.error(opt);
            }
        }
        $.ajax(option);
    },
    menuView: function (id, title, type, url) {
        kav7Admin.changePage({ id: id, title: title, type: type, url: url });
    },
    aJumpToUrl: function (url, msg) { // 网页跳转前提示
        if(url.indexOf(location.hostname) > -1){
            layui.util.openWin({
                url: url
            });
        } else {
            var op = {
                msg: `即将跳转到外部网站<br/>您将要访问的链接不属于 KA Admin，请关注您的账号安全。<br/><br/>` + msg + `:<span style="color:red;">` + url + "</span>",
                cb: function () {
                    layui.util.openWin({
                        url: url
                    });
                }
            };
            kaMsg.info(op);
        }
    },
    isAppPhoneOrExe: function () { //判断是否是手机端
        // console.log('是否在app中', jsBridge.inApp); jsBridge.view.openDevtools();
        var data = {
            code: "",
            type: "",
            appMsg: ""
        };
        if (/Mobi|Android|iPhone/i.test(navigator.userAgent)) {
            data.code = "200";
            data.type = "APP";//手机端
            data.appMsg = navigator.userAgent;
        } else {
            data.code = "500";
            data.type = "PC";//网页
            data.appMsg = navigator.userAgent;
        }
        return data;
    },
    imgOpenView: function (that) { //图片放大查看
        var imgsrc = $(that).attr("src");
        var alt = $(that).attr("alt");
        layer.photos({
            photos: {
                "title": "图片查看",
                "start": 0,
                "data": [
                    {
                        "alt": alt,
                        "pid": 1,
                        "src": imgsrc,
                    }
                ]
            }
        });
    },
    openFileView: function (title, url) {
        var b64Encoded = Base64.encode(url);
        url = 'http://localhost:8012/onlinePreview?url=' + encodeURIComponent(b64Encoded);
        top.layer.open({
            type: 1,
            title: title,
            content: `
            <div class="layui-row" style="height: 100%;">
                <div class="layui-col-xs12" style="height: 100%;">
                    <iframe id="1074" type="_iframe" scrolling="auto" frameborder="0" src="` + url + `" style="width:100%;height:100%;border-radius: 4px;" allowfullscreen="true"></iframe>
                </div>
            </div>
            `,
            area: ['100%', '100%'],
            shade: [0.6, '#FFF'], // 点击遮罩区域，关闭弹层
            scrollbar: false
        });
    },
    downloadFile: function (fileName, fileUrl) {
        const a = document.createElement('a');
        a.style.display = 'none';
        a.setAttribute('target', '_blank');
        fileName && a.setAttribute('download', fileName);
        a.href = fileUrl;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    },
    exec: function (string) { // 执行
        return new Function(string)();
    },
    automaticLoginTestAccount: function (a, p) { //自动登录测试账号
        if (a == undefined && p == undefined) {
            var option = kaValue.getUrl("getAutologintestaccount");
            var tenantId = $("#tenant").val();
            option.url = option.url + "/" + tenantId;
            option.async = false;
            option.success = function (re) {
                if (re.code == 200) {
                    var Autologintestaccounts = re.data;
                    if (Autologintestaccounts.length == 1) {
                        var Autologintestaccount = Autologintestaccounts[0];
                        $("#username").val(Autologintestaccount.account);
                        $("#password").val(Autologintestaccount.password);
                    } else if (Autologintestaccounts.length > 1) {
                        var htms = ``;
                        for (var i in Autologintestaccounts) {
                            var Autologintestaccount = Autologintestaccounts[i];
                            htms = htms + `<button onclick="ka.automaticLoginTestAccount('` + Autologintestaccount.account + `','` + Autologintestaccount.password + `')" class="layui-btn layui-btn-primary layui-border-blue">` + Autologintestaccount.account + `</button>`;
                        }
                        top.layer.open({
                            type: 1, // page 层类型
                            area: ['230px', '500px'],
                            shade: [0.6, '#FFF'], // 点击遮罩区域，关闭弹层
                            title: '快捷账号',
                            shade: 0,
                            anim: 0, // 0-6 的动画形式，-1 不开启
                            content: htms
                        });
                    }
                }
            }
            option.error = function (re) {
                return false;
            }
            ka.ajax(option);
        } else {
            $("#username").val(Autologintestaccount.account);
            $("#password").val(Autologintestaccount.password);
        }

    },
    getXmSelect: function (el, option) { // 获取下拉XmSelect
        option.el = "#" + el;
        $.extend(option, ka_grid_formDesignerSelect_option);
        option.on = function(data){
            //arr:  当前多选已选中的数据
            var arr = data.arr;
            //change, 此次选择变化的数据,数组
            var change = data.change;
            //isAdd, 此次操作是新增还是删除
            var isAdd = data.isAdd;
            alert('已有: '+arr.length+' 变化: '+change.length+', 状态: ' + isAdd);
        }
        var xmSelectX = xmSelect.render(option)
        top.ka_grid_formDesignerSelectMap.set(el, xmSelectX);
    },
    chooseToBringBack: function (grid, tag, id, number, bringBackLabelStr, bringBackReturnStr) {
        var chooseToBringBackGrid = {};
        var option = kaValue.getUrl("getGridById");
        option.url = option.url + "/" + id;
        option.async = false;
        option.success = function (re) {
            if (re.code == 200) {
                chooseToBringBackGrid = re.data;
            } else {
                kaMsg.error({ "code": re.code, "msg": re.msg });
            }
        }
        ka.ajax(option);
        var chooseToBringBackGridCode = chooseToBringBackGrid.code;
        layer.open({
            type: 2,
            title: this.title,
            area: ['95%', '95%'],
            content: 'gridChooseToBringBack.html?gridBodyId=' + chooseToBringBackGridCode + '&fbAnd=1&bringBackLabelStr=' + bringBackLabelStr,
            shade: [0.6, '#FFF'], // 点击遮罩区域，关闭弹层
            btn: ['选择带回', '取消'],
            btnAlign: 'r',
            yes: function (index, layero) {
                // 获取 iframe 的窗口对象
                var iframeWin = window[layero.find('iframe')[0]['name']];
                var chooseToBringBackForm = iframeWin.gridChooseToBringBackIndex.getData(number); // 获得 iframe 中某个输入框元素
                if (chooseToBringBackForm != null) {
                    var bringBackLabel = bringBackLabelStr.split(",");
                    var bringBackReturn = bringBackReturnStr.split(",");
                    var object = {};
                    for (var i in chooseToBringBackForm) {
                        var data = chooseToBringBackForm[i];
                        for (var j in bringBackReturn) {
                            var vk = bringBackReturn[j].split(":");
                            if (object[vk[1]] == undefined) {
                                object[vk[1]] = "";
                                object[vk[1]] = data[vk[0]];
                            } else {
                                object[vk[1]] = object[vk[1]] + "," + data[vk[0]];
                            }
                        }
                    }
                    for (var key in object) {
                        $("#" + key).val(object[key]);
                    }
                    layer.close(index);
                }
            }
        });
    },
    downloadJsonFile: function (jsonData, fileName) { // json 数据转换成json文件
        // 将JSON数据转换为字符串
        const jsonString = JSON.stringify(jsonData, null, 2); // 第二个参数用于美化输出，第三个参数是缩进空格数

        // 创建一个Blob对象
        const blob = new Blob([jsonString], { type: 'application/json;charset=utf-8' });

        // 创建一个指向Blob的URL
        const url = URL.createObjectURL(blob);

        // 创建一个下载链接
        const a = document.createElement('a');
        a.href = url;
        a.download = fileName || 'data.json'; // 如果没有提供文件名，则默认为'data.json'
        document.body.appendChild(a); // 将a标签添加到body中，以便能够触发点击事件
        a.click(); // 触发点击事件以开始下载

        // 清理：移除a标签并释放URL对象
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    },
    removeAddressPortAndQuery: function (urlString) {  // 去掉协议和主机部分，只保留路径和可能的哈希片段
        try {
            const url = new URL(urlString);
            return url.pathname + url.search + url.hash;
        } catch (e) {
            console.error('Invalid URL:', urlString);
            return '';
        }
    },
    openAddAndEditViewIndex: function (configure) { // 打开表格
        var title = configure.title;//标题
        var formDesignerId = configure.formDesignerId;//表格ID
        var formdesignerFormurlId = configure.formdesignerFormurlId;//按钮ID
        var fvStr = configure.fvStr;
        var width = configure.width;
        var height = configure.height;
        if (width == undefined || width == null || width == "") {
            width = "95%";
        }
        if (height == undefined || height == null || height == "") {
            height = "95%";
        }
        if (fvStr == undefined || fvStr == null || fvStr == "") {
            fvStr = "";
        } else {
            fvStr = "&fvStr=" + encodeURIComponent(encodeURI(JSON.stringify(fvStr)));
        }
        if (formDesignerId == undefined || formDesignerId == null || formDesignerId == "") {
            kaMsg.error({ "code": "500", "msg": "表格ID不能为空！" });
            return false;
        }
        if (formdesignerFormurlId == undefined || formdesignerFormurlId == null || formdesignerFormurlId == "") {
            kaMsg.error({ "code": "500", "msg": "按钮ID不能为空！" });
            return false;
        }
        var KaSubmitway = "";
        var submiturl = "";
        var option = kaValue.getUrl("SysFormdesignerFormurGetInfo");
        option.url = option.url + "/" + formdesignerFormurlId;
        option.async = false;
        option.success = function (re) {
            if (re.code == 200) {
                KaSubmitway = re.data.submitway;
                submiturl = re.data.submiturl;
            }
        }
        option.error = function (re) {
            return false;
        }
        ka.ajax(option);
        //加载
        var index = layer.open({
            type: 2,
            title: title,
            area: [width, height],
            content: 'addAndEditView.html?formDesignerId=' + formDesignerId + "&formdesignerFormurlId=" + formdesignerFormurlId + fvStr,
            shade: [0.6, '#FFF'], // 点击遮罩区域，关闭弹层
            btn: ['提交', '取消'],
            btnAlign: 'r',
            yes: function (index, layero) {
                // 获取 iframe 的窗口对象
                var iframeWin = window[layero.find('iframe')[0]['name']];
                var formPreviewForm = iframeWin.addAndEditViewIndex.getData(); // 获得 iframe 中某个输入框元素
                if (formPreviewForm != null) {
                    if (KaSubmitway != undefined && KaSubmitway != null && KaSubmitway != "") {
                        if (KaSubmitway == "1") {
                            formPreviewForm.id = d.data.id;
                        }
                    }
                    if(configure.cbType == 2){
                        configure.cb(formPreviewForm);
                    } else {
                        var option = kaValue.getUrl(submiturl);
                        option.data = formPreviewForm;
                        option.success = function (re) {
                            if (re.code == 200) {
                                if(configure.cbType != undefined && configure.cbType != null && configure.cbType != "") {
                                    if(configure.cbType == 1){
                                        layer.close(index);
                                    }
                                } else {
                                    layer.close(index);
                                    kagrid.getData(config, function (reData, config) {
                                        var gridApi = kagrid.getGridApi(config.id);
                                        gridApi.setRowData(reData);
                                        kagrid.playUpSort(config);
                                        kaMsg.success(re);
                                    })
                                }
                                
                            } else {
                                kaMsg.error({ "code": re.code, "msg": re.msg });
                            }
                        }
                        ka.ajax(option);
                    }
                }
            }
        });
    },
    kalLayerVer: function (configure) { //弹出验证
        var katype = configure.katype;
        if(katype == undefined || katype == null || katype == ""){
            layer.alert("请选择打开方式", {
                title: false,
                btn: ['内部弹窗', '浏览器新页签', '内部页签'], 
                btnAlign: 'c', // 按钮居中显示
                btn1: function () {
                    ka.kalLayer(configure);
                },
                btn2: function () {
                    ka.aJumpToUrl(configure.content,"");
                },
                btn3: function () {
                    ka.menuView("99999",configure.title == undefined?"页签打开":configure.title,"C",configure.content)
                }
            });
        } else {
            if(katype == 1){
                ka.kalLayer(configure);
            } else if(katype == 2){
                ka.aJumpToUrl(configure.content,"");
            } else if(katype == 3){
                ka.menuView("99999",configure.title == undefined?"页签打开":configure.title,"C",configure.content)
            }
        }
    },
    kalLayer: function(configure){// ka Layui弹窗
        var defaultConfigure = {
            type: 2, // page 层类型
            area: ['95%', '95%'],
            title: "",
            shadeClose: true, // 点击遮罩区域，关闭弹层
            maxmin: false, // 允许全屏最小化
            anim: 0, // 0-6 的动画形式，-1 不开启
            shade: [0.6, '#FFF'] // 点击遮罩区域，关闭弹层
        };
        var newconfigure = $.extend(defaultConfigure,configure)
        top.layer.open(newconfigure);
    }
}
// ka 业务重复代码
var kaBuss = {
    kaCookieClear: function () {//统一清除登录信息
        kaCookie.clear("Admin-Token");
        kaCookie.clear("Authorization");
        kaCookie.clear("JSESSIONID");
        kaCookie.clear("password");
        kaToken.clear();
    },
    kaCookieClear2: function () {//统一清除登录信息
        kaBuss.kaCookieClear();
        kaCookie.clear("username");
        kaCookie.clear("tenant");
        kaCookie.clear("rememberMe");
        kaCookie.clear("tenantId");
        kaToken.clear();
    },
    locationLoginHref: function () { // 跳转登录页面
        top.window.location.href = "login.html";
    },
    locationHomeHref: function () { // 跳转登录页面
        top.window.location.href = "home.html";
    }
}
//设置当前用户
var kaCurrUser = {
    get: function () {
        return localStorage.getItem("kaLoginDataParam");
    },
    set: function (kaLoginDataParam) {
        localStorage.setItem("kaLoginDataParam", JSON.stringify(kaLoginDataParam))
    },
    getBusinessCard: function (opt) {
        var businessCardArray = [];
        var id = ""; //ID
        var avatar = ""; //头像
        var nickName = ""; //昵称
        var phonenumber = ""; //手机号
        var email = "";//邮箱
        var dept = "";//部门
        var tenantName = "";//租户
        var signature = "";//签名
        var accountLevel = "";//账号等级
        var mylocation = "";//所在地
        var privilegeHtml = "";//特权
        var tenantAuthenticationStatus = "";//公司是否认证
        if (opt == undefined || opt.id == undefined || opt.id == "") {
            var option = kaValue.getUrl("getUserBusinessCard");
            option.async = false;
            option.success = function (re) {
                var user = re.user;
                id = user.userId; //ID
                avatar = user.avatar; //头像
                nickName = user.nickName; //昵称
                phonenumber = user.phonenumber; //手机号
                email = user.email;//邮箱
                dept = user.depString;//部门
                tenantName = user.tenantName;//租户
                signature = user.signature;//签名
                accountLevel = user.accountLevel;//账号等级
                mylocation = user.mylocation;//所在地
                privilegeHtml = kaCurrUser.getPrivilegeHtml(user.privilege);//特权
                tenantAuthenticationStatus = user.tenantAuthenticationStatus;//公司是否认证
            }
            ka.ajax(option);
        } else {
            var option = kaValue.getUrl("getUserBusinessCard");
            option.url = option.url + "?userid=" + opt.id;
            option.async = false;
            option.success = function (re) {
                var user = re.user;
                id = user.userId; //ID
                avatar = user.avatar; //头像
                nickName = user.nickName; //昵称
                phonenumber = user.phonenumber; //手机号
                email = user.email;//邮箱
                dept = user.depString;//部门
                tenantName = user.tenantName;//租户
                signature = user.signature;//签名
                accountLevel = user.accountLevel;//账号等级
                mylocation = user.mylocation;//所在地
                privilegeHtml = kaCurrUser.getPrivilegeHtml(user.privilege);//特权
                tenantAuthenticationStatus = user.tenantAuthenticationStatus;//公司是否认证
            }
            ka.ajax(option);
        }
        if (avatar == undefined || avatar == null || avatar == "" || avatar == "null") {
            avatar = "admin/images/logo1.png";
        }
        var remarksOrSignatureTitle = "设置备注";
        var option = kaValue.getUrl("verRemarksOrSignature");//获取获取公示栏
        option.async = false;
        option.url = option.url + "/" + id
        option.success = function (re) {
            if (re.code == 200) {
                if (re.type == 1) {
                    remarksOrSignatureTitle = "设置签名";
                }
            } else {
                kaMsg.error(re);
            }
        }
        ka.ajax(option);
        var html = `
            <div class="businessCardDiv1">
                <div class="businessCardDiv2">
                    <div class="weui-cells businessCardDiv3">
                        <div class="weui-cell businessCardDiv4">
                            <div class="weui-cell__hd businessCardDiv5">
                                <img src="` + (kaValue.ctx() + avatar) + `" onclick="ka.imgOpenView(this);" class="businessCardImg">
                                <div class="businessCardVIP">
                                    <img src="/static/images/vip/vip` + accountLevel + `.png" class="businessCardVIPImg">
                                </div>
                            </div>
                            <div class="weui-cell__bd" style="height: 90px;">
                                <p class="businessP1">` + nickName + `</p>
                                <p class="businessP2">` + signature + `</p>
                                <div class="businessP3">
                                    <div style="height: 45px;width: 100%;margin-top: 5px;">
                                        ` + privilegeHtml + `
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="weui-cell cellTwo businessCardDiv6">
                            <div class="weui-cell__bd">
                                <div class="weui-flex">
                                    <div class="weui-flex__item businessPX">
                                        <button onclick="kaCurrUser.openSharedFiles('` + id + `')" type="button" class="layui-btn-primary layui-border-blue layui-btn-sm businessCardButton">
                                            <i class="icon iconfont icon-fenxiang businessCardI"></i> 共享文件
                                        </button>
                                    </div>
                                    <div class="weui-flex__item businessPX">
                                        <button id="remarksOrSignature" onclick="kaCurrUser.openRemarksOrSignature('` + id + `')" type="button" class="layui-btn-primary layui-border-blue layui-btn-sm businessCardButton">
                                            <i class="icon iconfont icon-cog businessCardI"></i> ` + remarksOrSignatureTitle + `
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="weui-cell weui-cell_access businessCardWeuiCell" style="padding-top: 10px;">
                            <div class="businessCardDiv7">
                                <p class="businessCardSpan" style="letter-spacing: 2px;">所在地</p>
                            </div>
                            <div class="weui-cell__bd">
                                <p class="businessCardP">` + mylocation + `</p>
                            </div>
                        </div>
                        <div class="weui-cell weui-cell_access weuiCellKa businessCardWeuiCell">
                            <div class="businessCardDiv7">
                                <p class="businessCardSpan" style="letter-spacing: 20px;">手机</p>
                            </div>
                            <div class="weui-cell__bd">
                                <p class="businessCardP">` + phonenumber + `</p>
                            </div>
                        </div>
                        <div class="weui-cell weui-cell_access weuiCellKa businessCardWeuiCell">
                            <div class="businessCardDiv7">
                                <p class="businessCardSpan" style="letter-spacing: 20px;">邮箱</p>
                            </div>
                            <div class="weui-cell__bd">
                                <p class="businessCardP">` + email + `</p>
                            </div>
                        </div>
                        <div class="weui-cell weui-cell_access weuiCellKa businessCardWeuiCell">
                            <div class="businessCardDiv7">
                                <p class="businessCardSpan" style="letter-spacing: 20px;">部门</p>
                            </div>
                            <div class="weui-cell__bd">
                                <p class="businessCardP">` + dept + `</p>
                            </div>
                        </div>
                        <div class="weui-cell weui-cell_access weuiCellKa businessCardWeuiCell">
                            <div class="businessCardDiv7">
                                <p class="businessCardSpan" style="letter-spacing: 20px;">企业</p>
                            </div>
                            <div class="weui-cell__bd">
                                <span class="businessCardP">
                                    <span>` + tenantName + `</span>
                                    ` + (tenantAuthenticationStatus == 1 ? `<i style="color:green;font-size: 13px;" class="icon iconfont icon-supervise"></i>` : "") + `
                                </span>
                            </div>
                        </div>
                        <div class="weuiCellKa" style="height:87px">
                        <div style="width: 120px;padding: 5px 0px;float: left;padding-right:5px">
                                <img src="../../static/images/ad/ggzz.jpg" style="width: 100%;height: 100%;border-radius: 5px;">
                            </div>
                            <div style="width: calc(100% - 125px);padding: 0px;float: left;height: 100%;">
                                <div class="scrollbox" id="scrollbox_` + id + `"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            `;
        businessCardArray.push(id);
        businessCardArray.push(html);
        return businessCardArray;
    },
    getPrivilegeHtml: function (ids) {// 获取特权图标
        var html = ``;
        var privilegeData = [];
        var option = kaValue.getUrl("SysPrivilegeGetInfos");//获取获取公示栏
        option.async = false;
        option.url = option.url + "/" + ids
        option.success = function (re) {
            if (re.code == 200) {
                privilegeData = re.data;
            } else {
                kaMsg.error(re);
            }
        }
        ka.ajax(option);
        for (var i in privilegeData) {
            html = html + `<div class="getPrivilegeHtmlDiv" style="background: ` + (privilegeData[i].bgcolor != undefined && privilegeData[i].bgcolor != null && privilegeData[i].bgcolor != "" ? privilegeData[i].bgcolor : "#0066ff") + `;"><i style="color: ` + (privilegeData[i].color != undefined && privilegeData[i].color != null && privilegeData[i].color != "" ? privilegeData[i].color : "#fff") + `;" class="icon iconfont ` + privilegeData[i].icon + `"></i></div>`;
        }
        return html;
    },
    openSharedFiles: function (id) { //打开共享文件
        var gridBody = {
            id: "fileSharedlistGrid",
            fsv: {},
            fv: [],//查询条件
            button: {
                type: 0, //【1:URL,2:本地JSON,3:外站URL,4:自定义JSON】
                datajson: null
            },
            column: [
                { headerName: '文件编码', field: 'code', kaSort: true },
                { headerName: '文件名称', field: 'name', kaSort: true },
                { headerName: '文件类型', field: 'fileType', kaSort: true },
                { headerName: '文件大小', field: 'fileSize', kaSort: true },
                { headerName: 'MD5文件编码', field: 'mdWuId', kaSort: true }
            ]
        };
        var gridDivHtml = kagrid.getHtml(gridBody);
        layer.open({
            type: 1,
            shadeClose: true,
            shade: [0.6, '#FFF'], // 点击遮罩区域，关闭弹层
            area: ['58%', '60%'],
            title: false,
            dataType: 4,
            content: `<div style="width: 99%;height: calc(100% - 6px);margin: 3px auto;">` + gridDivHtml + `</div>`,
            success: function () {
                kagrid.loading(gridBody);
            }
        });
    },
    openRemarksOrSignature: function (id) { //打设置备注或者修改签名
        var option = kaValue.getUrl("verRemarksOrSignature");//获取获取公示栏
        option.async = false;
        option.url = option.url + "/" + id
        option.success = function (re) {
            if (re.code == 200) {
                var title = '请输入备注';
                var oldvalue = re.data;
                if (re.type == 1) {
                    title = '请输入签名';
                }
                layer.prompt({ title: title, formType: 2, value: oldvalue }, function (value, index, elem) {
                    if (value === '') return elem.focus();
                    var option = kaValue.getUrl("updateRemarksOrSignature");//获取获取公示栏
                    option.async = false;
                    option.data = {
                        id: id,
                        type: 1,
                        value: value
                    }
                    option.success = function (rex) {
                        if (rex.code == 200) {
                        } else {
                            kaMsg.error(rex);
                        }
                    }
                    ka.ajax(option);
                    // 关闭 prompt
                    layer.close(index);
                });
            } else {
                kaMsg.error(re);
            }
        }
        ka.ajax(option);
    }
}
//设置Token
var kaToken = {
    get: function () { //获取token
        return localStorage.getItem("ka_token");
    },
    set: function (tk) { // 设置token
        localStorage.setItem("ka_token", tk);
    },
    clear: function () { // 清除token
        localStorage.removeItem("ka_token");
    }
}
//设置Cookie
var kaCookie = {
    get: function (name) { },
    set: function (name, value, day, path, domain) {
        $.cookie(name, value, { domain: domain, path: "/", expires: day })
    },
    clear(name) {
        $.removeCookie(name, null, { path: '/' });
    },
}
//设置表单
var kaForm = {
    init: function (option) {
        layui.form.on(option.id, function (data) {
            var field = data.field;
            //验证
            var verifyBoolean = false;
            try {
                verifyBoolean = option.kaver(field);
                if (verifyBoolean == undefined || verifyBoolean == null || verifyBoolean == "") {
                    verifyBoolean = true;
                }
                // 方法存在
            } catch (error) {
                verifyBoolean = true;
            }
            //提交
            option.cb(field);
            return false;
        });
    }
}
//消息提示
var kaMsg = {
    html: function (op) {
        // var prompt = `<i class="icon iconfont icon-ask"></i>`;
        var html = `<div style="color: ` + (op.type == "error" ? `red` : op.type == "success" ? `green` : op.type == "warn" ? `#ff9000` : ``) + ` ;">`
            + op.msg +
            `</div>`
            + (op.type == "error" ? `错误编码：<span style="color: red;">` + op.code + `</span style="margin-right: 30px;"><a style="color: #0060ef;margin-left: 50px;"> 前往社区 》 </a>` : ``)
            ;
        return html
    },
    mask: function () { //遮罩
        top.layer.confirm("<img src='/component/kav7/images/1485.gif' />", {
            title: '',
            skin: 'layui-layer-loading1', // 2.8+
            shade: [0.8, '#FFF'], // 点击遮罩区域，关闭弹层
            area: ['90%', 'auto'],
            btn: false,
            offset: 'auto',
            anim: 5
        });
    },
    loading1: function () {// 加载层1
        return kaMsg.loading({ type: 1 });
    },
    loading: function (opt) {//加载
        var loadingUUID = ka.uuidStr();
        if (opt.type == 1) {//普通
            var layerIndex = top.layer.confirm("<img src='/component/kav7/images/1485.gif' />", {
                title: '',
                skin: 'layui-layer-loading1', // 2.8+
                shade: [0.8, '#FFF'], // 点击遮罩区域，关闭弹层
                area: ['90%', 'auto'],
                btn: false,
                offset: 'auto',
                anim: 5
            });
            top.ka_layer_loadingMap.set(loadingUUID, layerIndex);
        }
        return loadingUUID;
    },
    loadingClose: function (loadingUUID) {
        if (loadingUUID != undefined && loadingUUID != null && loadingUUID != "") {
            top.layer.close(top.ka_layer_loadingMap.get(loadingUUID));
            top.ka_layer_loadingMap.delete(loadingUUID);
        }
    },
    success: function (opt) {// 成功
        if (opt.returnMsgId == undefined || opt.returnMsgId == null || opt.returnMsgId == "") {
            var success = `<span style="color: green;font-size: 14px;"><i class="layui-icon layui-icon-success" style="margin-right: 9px;"></i>`;
            opt.type = "success";
            var html = kaMsg.html(opt);
            top.layer.confirm(html, {
                title: success + "成功信息</span>",
                skin: 'layui-layer-success', // 2.8+
                shade: [0.6, '#FFF'], // 点击遮罩区域，关闭弹层
                area: ['90%', 'auto'],
                btn: false,
                offset: 't',
                anim: 5,
                time: 1000
            });
        } else {
            var fbAndObject = [{
                "field": "jsonResult",
                "equation": "101",
                "andOr": "and",
                "value": opt.returnMsgId,
                "nal": "10001"
            }]
            var fvStr = JSON.stringify(fbAndObject);
            fvStr = encodeURIComponent(encodeURI(fvStr));
            top.layer.open({
                type: 2,
                title: '查看结果',
                shadeClose: true,
                maxmin: false, //开启最大化最小化按钮
                shade: [0.6, '#FFF'], // 点击遮罩区域，关闭弹层
                area: ['80%', '80%'],
                content: 'grid.html?gridBodyId=dataUpdataLogREGrid&fbAnd=1&fvStr=' + fvStr
            });
        }
    },
    error: function (opt) {// 错误
        kalog.outLogs(["错误编码：", opt]);
        if (opt.msg == "数据中心为空" || opt.msg == "登录已过期，请重新登录") {
            var kaindexpagestr = sessionStorage.getItem("indexpage");
            if (kaindexpagestr != undefined && kaindexpagestr != null && kaindexpagestr != "") {
                kaindexpagestr = "?indexpage=" + kaindexpagestr;
            } else {
                kaindexpagestr = "";
            }
            kaCookie.clear("Admin-Token");
            kaCookie.clear("Authorization");
            kaCookie.clear("JSESSIONID");
            kaCookie.clear("password");
            kaCookie.clear("password");
            kaToken.clear();
            window.location.href = "../login.html" + kaindexpagestr;
        } else {
            if (opt.returnMsgId == undefined || opt.returnMsgId == null || opt.returnMsgId == "") {
                var error = `<span style="color: red;font-size: 14px;"><i class="layui-icon layui-icon-error" style="margin-right: 9px;"></i>`;
                opt.type = "error";
                var html = kaMsg.html(opt);
                top.layer.confirm(html, {
                    title: error + "失败信息</span>",
                    btnAsync: true,
                    btn: ['发送给管理员', '知道了'], //按钮
                    shade: [0.6, '#FFF'], // 点击遮罩区域，关闭弹层
                    skin: 'layui-layer-error', // 2.8+
                    area: ['90%', 'auto'],
                    offset: 't',
                    anim: 5
                }, function (index, layero, that) {
                    var defer = $.Deferred();
                    that.loading(true);
                    sleep(1000).then(defer.resolve);
                    return defer.promise();
                });
            } else {
                var fbAndObject = [{
                    "field": "jsonResult",
                    "equation": "101",
                    "andOr": "and",
                    "value": opt.returnMsgId,
                    "nal": "10001"
                }]
                var fvStr = JSON.stringify(fbAndObject);
                fvStr = encodeURIComponent(encodeURI(fvStr));
                top.layer.open({
                    type: 2,
                    title: '查看结果',
                    shadeClose: true,
                    maxmin: false, //开启最大化最小化按钮
                    shade: [0.6, '#FFF'], // 点击遮罩区域，关闭弹层
                    area: ['80%', '80%'],
                    content: 'grid.html?gridBodyId=dataUpdataLogREGrid&fbAnd=1&fvStr=' + fvStr
                });
            }
        }
    },
    warn: function (opt) {// 警告
        var warn = `<span style="color: #ff9000;font-size: 14px;"><i class="layui-icon layui-icon-warn" style="margin-right: 9px;"></i>`;
        opt.type = "warn";
        var html = kaMsg.html(opt);
        top.layer.confirm(html, {
            title: warn + "警告信息</span>",
            btnAsync: true,
            btn: ['确定继续', '关闭'], //按钮
            skin: 'layui-layer-warn', // 2.8+
            shade: [0.6, '#FFF'], // 点击遮罩区域，关闭弹层
            area: ['90%', 'auto'],
            offset: 't',
            anim: 5
        }, function (index, layero, that) {
            opt.cb();
            layer.close(index);
        });
    },
    info: function (opt) {// 警告
        opt.type = "info";
        var warn = `<span style="color: #0066ff;font-size: 14px;"><i class="layui-icon layui-icon-warn" style="margin-right: 9px;"></i>`;
        var html = kaMsg.html(opt);
        top.layer.confirm(html, {
            title: warn + "消息确认</span>",
            btnAsync: true,
            btn: ['确定继续', '关闭'], //按钮
            skin: 'layui-layer-warn', // 2.8+
            shade: [0.6, '#FFF'], // 点击遮罩区域，关闭弹层
            area: ['90%', 'auto'],
            anim: 5
        }, function (index, layero, that) {
            opt.cb();
            layer.close(index);
        });
    },
    prompt: function () {// 提示
        opt.type = "prompt";
    }
}